import _config from '@/config'
import { buildQueryString } from '@/utils'

// let interrupted = false // 避免重复报错
export const request = (options = {}) => {
  return new Promise((resolve, rejects) => {
    const token = uni.getStorageSync('Token') || null
    let headers = {
      'Token-Type': 'APP',
      Accountid: uni.getStorageSync('accountId') || '',
      Authorization: token,
      'content-type': 'application/x-www-form-urlencoded'
    }

    headers = Object.assign(headers, options.headers)

    const domain = uni.getStorageSync('proxyUrl')
      ? uni.getStorageSync('proxyUrl')
      : _config.baseURL
    let url = `${domain}${options.url}`

    // 如果有params
    if (options.params) {
      url = `${domain}${options.url}?${buildQueryString(options.params)}`
    }

    // if (!token) interrupted = true

    uni.request({
      url,
      method: options.method || 'GET',
      data: options.data || {},
      header: headers,
      success: (res) => {
        // if (res.statusCode !== 200) {
        //   interrupted = true
        //   if (!interrupted) {
        //     uni.$u.toast(res.data.msg)
        //   }
        // }
        const { data } = res
        const statusCode = res.statusCode
        // if (data.code !== 200) {
        //   uni.$u.toast(data.msg)
        if (statusCode === 302 || statusCode === 401) {
          // 如果token过期清除代理地址
          // uni.removeStorageSync('proxyUrl')
          // uni.removeStorageSync('Token')
          // uni.removeStorageSync('accountId')
          // uni.removeStorageSync('userInfo')
          uni.clearStorageSync()
          uni.showModal({
            title: '提示',
            content: 'token失效请重新登录，点击取消停留此页面。',
            success: function (res) {
              if (res.confirm) {
                wx.redirectTo({
                  url: '/pages/login/index'
                })
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })
          return
        }

        // }
        resolve(data.data)
      },
      fail: (error) => {
        console.log('这次报错走这里')
        console.log(error)
        // rejects(error)
      }
    })
  })
}
